import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/open_page_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/goods/goods_list_widget.dart';
import 'package:gzmall_app/goods/home_goods_list_page.dart';
import 'package:gzmall_app/home/actives_page.dart';
import 'package:gzmall_app/home/brand_list_page.dart';
import 'package:gzmall_app/home/clearance_list_page.dart';
import 'package:gzmall_app/mine/order_details.dart';
import 'package:gzmall_app/mine/order_page.dart';
import 'package:gzmall_app/model/message.dart';
import 'package:gzmall_app/store/near_store_list_page.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/topup/topup_page.dart';

class MessageCenterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MessageCenterPageState();
  }
}

class MessageCenterPageState extends State<MessageCenterPage> {
  List<Message> _messageList = [];
  int _curIndex;

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  @override
  void initState() {
    super.initState();
    _getMessages(1);
  }

  @override
  Widget build(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: _messageList != null ? _messageList.length : 0,
        itemBuilder: (context, index) {
          Message message = _messageList[index];
          return Slidable(
            delegate: SlidableDrawerDelegate(),
            actionExtentRatio: 0.25,
            child: Container(
              color: Colors.white,
              margin: const EdgeInsets.only(bottom: 1.0),
              child: new ListTile(
                title: Text(message.name),
                onTap: () {
                  _readMessage(message.id);
                  OpenPageUtil.openPage(context, message?.pageType,
                      message?.pageUrl, message?.params,
                      name: message?.name);
                },
              ),
            ),
            secondaryActions: <Widget>[
              IconSlideAction(
                caption: '删除',
                color: Colors.red,
                icon: Icons.delete,
                onTap: () {
                  _curIndex = index;
                  _deleteMessage(message.id);
                },
              ),
            ],
          );
        },
      ),
      showEmpty: _showEmpty,
      onReload: () {
        _getMessages(1);
      },
    );
    return new Scaffold(
      appBar: _createAppBar(),
      body: new Container(
        color: ColorCommon.grey2,
        child: _refreshListView,
      ),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("消息中心"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getMessages(1);
    } else {
      _getMessages(_curPage + 1);
    }
  }

  _getMessages(int page) {
    bool isGetNew = page == 1;
    Map<String, String> params = {"page": page.toString()};
    NetUtil.get(
        context,
        Api.notifications,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Message.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _messageList = _dataList;
            } else {
              _messageList.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty =
                isGetNew && (_messageList == null || _messageList.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }

  _readMessage(int id) {
    NetUtil.put(
      context,
      Api.notifications + "/" + id.toString(),
      (data, message) {},
    );
  }

  _deleteMessage(int id) {
    NetUtil.delete(context, Api.notifications + "/" + id.toString(),
        (data, message) {
      ToastUtil.showMessageToast(message);

      if (!mounted) return;
      setState(() {
        if (_messageList != null && _messageList.length > _curIndex) {
          _messageList.removeAt(_curIndex);
        }
      });
    });
  }
}
